/*
 * @Descripttion: OSS
 * @version:
 * @Author: wellington
 * @Date: 2021-11-23 11:15:33
 */

import TinyOSS from 'tiny-oss'
import { getOSSToken } from '@/api'

// 官方文档https://help.aliyun.com/document_detail/64041.html
export const ossUpload = async file => {
  getOSSToken().then(({ region, accessKeyId, accessKeySecret, stsToken }) => {
    const client = new TinyOSS({
      // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
      region,
      // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
      accessKeyId,
      accessKeySecret,
      stsToken,
      // 填写Bucket名称。
      bucket: 'examplebucket'
    })
    postImg(client, file)
  })
}

async function postImg(client, file) {
  try {
    // object表示上传到OSS的文件名称。
    // file表示浏览器中需要上传的文件，支持HTML5 file和Blob类型。
    const r1 = await client.put('object', file)
    console.log('put success: %j', r1)
    const r2 = await client.get('object')
    console.log('get success: %j', r2)
  } catch (e) {
    console.error('error: %j', e)
  }
}

export const getImgToBase64 = (file, callback) => {
  const img = new Image()
  const reader = new FileReader()
  //缩放图片需要的canvas
  let canvas = document.createElement('canvas')
  let context = canvas.getContext('2d')

  reader.readAsDataURL(file)
  //文件base64化，以便获知图片原始尺寸
  reader.onload = function (even) {
    img.src = even.target.result
  }
  //base64地址图片加载完毕后
  img.onload = function () {
    //图片原始尺寸
    let originWidth = this.width
    let originHeight = this.height
    //最大尺寸限制
    let maxWidth = 400
    let maxHeight = 400
    //目标尺寸
    let targetWidth = originWidth
    let targetHeight = originHeight
    //图片尺寸超过400*400的限制
    if (originWidth > maxWidth || originHeight > maxHeight) {
      if (originWidth / originHeight > maxWidth / maxHeight) {
        //更宽，按照宽度限定尺寸
        targetWidth = maxWidth
        targetHeight = Math.round(maxWidth * (originHeight / originWidth))
      } else {
        targetHeight = maxHeight
        targetWidth = Math.round(maxHeight * (originWidth / originHeight))
      }
    }
    //canvas对图片进行缩放
    canvas.width = targetWidth
    canvas.height = targetHeight
    //清除画布
    context.clearRect(0, 0, targetWidth, targetHeight)
    //图片压缩
    context.drawImage(img, 0, 0, targetWidth, targetHeight)
    const dataURL = canvas.toDataURL(file.type || 'image/jpeg', 0.92)
    callback(dataURL)
    //canvas转为blob并上传
    // canvas.toBlob(function (blob) {
    //   //图片ajax上传
    //   const formData = new FormData()
    //   formData.append('file', blob)
    //   //调用上传图片接口
    //   //axios.post('http://xxx.com/api',formData);
    //   //清除内容
    //   //e.target.value = '';
    // }, file.type || 'image/png')
  }
}
